const fs = require('fs');
var https = require('https');
var qs = require('querystring');

const accessToken = require('./access_token');
const puppeteer = require('puppeteer');

(async () => {
	const browser = await puppeteer.launch({
		headless: false,
		args: ["--no-sandbox", ]
	});
	const page = await browser.newPage();
	await page.goto('http://iir.circ.gov.cn/web/');
	await page.setViewport({
		width: 1920,
		height: 750
	});

	var access_tokenObj = await accessToken()
	var access_token = JSON.parse(access_tokenObj).access_token

	page.on('dialog', async dialog => {
		console.log('监听对话框');
		console.log(dialog.message());
		await dialog.dismiss();
	});


	await page.screenshot({
		path: 'example.png',
		clip: {
			x: 1300,
			y: 220,
			width: 200,
			height: 150
		}
	});
	console.log('截图');

	function getNumber() {
		return new Promise((resolve, reject) => {
			// 读取文件数据
			let imgData = fs.readFileSync('./example.png').toString('base64');

			var postData = qs.stringify({
				image: imgData
			})
			var options = {
				hostname: 'aip.baidubce.com',
				path: '/rest/2.0/ocr/V1/numbers?access_token=' + access_token,
				method: 'POST',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
				}
			};

			var req = https.request(options, function(res) {
				var data = ''
				res.on('data', (chunk) => {
					data += chunk
				})
				res.on('end', () => {
					var numbers = JSON.parse(data).words_result[0].words
					resolve(numbers)
					console.log('破解验证码:', numbers);


				})
			});
			// 携带数据发送https请求
			req.write(postData);
			req.end();
		})
	}


	const numbers = await getNumber()
	await page.focus('input[name=name]');
	console.log('定位焦点到姓名输入框');
	var name = '王鹏'
	await page.keyboard.sendCharacter(name);
	console.log('本次输入名字',name);

	await page.focus('#valcode0');
	console.log('定位焦点到验证码框');
	await page.keyboard.sendCharacter(numbers);
	console.log('输入验证码:', numbers);


	await page.waitFor(3000);

	await page.click("img[src='images_new/button_cx.jpg']");
	console.log('点击搜索按钮');

	browser.on('targetcreated', async (target) => {
		console.log(`Created target type ${target.type()} url ${target.url()}`);
		if (target.type() !== 'page') {
			return;
		} else {
			var pages = await target.page();
			const ksbm_bg = await pages.$('#pm')
			console.log('结果页成功打开,开始获取数据...');
			
			const srcs = await pages.evaluate(() => {
			  const data = document.querySelectorAll('.cxjg tr');
			  return Array.prototype.map.call(data, item => item.innerText);
			});
			
			console.log(`获得 ${srcs.length} 结果, 保存`);
			console.log(srcs)
			
			fs.writeFile('./data.txt', srcs, 'utf8', async function(err){
				if(err) throw err;
				console.log('文件写入成功');
				console.log('耗时');
				console.timeEnd('useTime');
				 // await browser.close();
			});
		}
	});





	// 	 page.on('load',async ()=>{
	// 		 console.log('结果页成功打开,开始获取数据...');
	//  
	// 		 await page.screenshot({
	// 			 path: 'result.png',
	// 		 });
	// 		 console.log('截图');
	// 	 
	// 		 await browser.close();
	// 		 console.log('关闭浏览器');
	//  
	// 	 })




})();
